package com.party.course.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.party.common.constant.Constants;
import com.party.common.utils.PageUtils;
import com.party.common.utils.StringUtils;
import com.party.course.domain.PlanClass;
import com.party.course.domain.StudentInfo;
import com.party.generator.util.VelocityInitializer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送企业微信机器人群消息工具类
 *
 * @author songkaiyue
 * @date 2022-06-09
 *
 */
public class SendQWmsgUtil {

    private static final Logger log = LoggerFactory.getLogger(SendQWmsgUtil.class);

    public static void main(String[] args) {
//        String appId = "wx0fa07a6c70897e68";
//        String appSecret = "625080e0d87e75343781460af32c3fe7";
//        String url = generateUrlLink(appId, appSecret,"");
//        System.out.println(url);
//        // 使用JSONObject封装参数
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("path", "/pages/publishHomework/publishHomework");
//        jsonObject.put("query", "");
//        jsonObject.put("expire_type", 1);
//        jsonObject.put("expire_interval", 1);
//        jsonObject.put("env_version", "release");
//
//        // 封装 cloud_base 对象
//        JSONObject cloudBase = new JSONObject();
//        cloudBase.put("env", "xxx");
//        cloudBase.put("domain", "xxx.xx");
//        cloudBase.put("path", "/jump-wxa.html");
//        cloudBase.put("query", "a=1&b=2");
//
//        // 将 cloud_base 对象添加到主对象中
//        jsonObject.put("cloud_base", cloudBase);
//
//        // 打印最终的JSONObject字符串
//        System.out.println(jsonObject.toString());

//        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=0160e042-bb6d-4936-8c87-943e83a69411";
//        String key = url.substring(url.indexOf("key=") + 4);
//        System.out.println("Key: " + key);

//        String time1 = "13:00"; // 示例时间
//        System.out.println(DateTimeUtill.formatTime(time1));
//        String time2 = "18:00"; // 示例时间
//        System.out.println(DateTimeUtill.getToTime(time2));
//        String date = "2025-06-07";
//        System.out.println(DateTimeUtill.getWeek(date));



        // 渲染模板
        VelocityInitializer.initVelocity();
        VelocityContext context = new VelocityContext();
        context.put("className", "珠心算");
        context.put("classType", "试课");
        context.put("stuName", "张三");
        context.put("day", "6月10日 星期二");
        context.put("time", "上午 9:00-10:30");
        context.put("nowDateTime", "2025-6-9 14:31:28");
        context.put("remark", "轮排派单");
        String appId = "wx0fa07a6c70897e68";
        context.put("appId", appId);
        context.put("stuId", "1111111111");
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate("vm/massage.vm", Constants.UTF8);
        tpl.merge(context, sw);
        String content = sw.toString();
        System.out.println(content);
//        // 发送POST请求
        sendPostRequest(content,"");
    }

    /**
     * 根据排课数据 通过机器人向企微群聊发送派单消息
     * @param studentInfo
     * @param requestUrl
     */
    public static void sendMsg(StudentInfo studentInfo, String requestUrl) {
        if (StrUtil.isEmpty(studentInfo.getExpectTime())) {
            throw new RuntimeException("缺少期望上课时间！");
        }
        //处理期望上课的时间格式
        String[] parts = studentInfo.getExpectTime().split(" ");
        String date = parts[0];
        String timePart = parts[1];
        // 转换日期为星期几
        String weekDay = DateTimeUtill.getWeek(date);
        // 转换时间为 12 小时制格式
        String paramTime = DateTimeUtill.formatTime(timePart);
        //转换成带有上午/下午的时间格式
        String toTime = DateTimeUtill.getToTime(paramTime);

        // 渲染模板
        VelocityInitializer.initVelocity();
        VelocityContext context = new VelocityContext();
        context.put("className", studentInfo.getClassName());
        context.put("classType", studentInfo.getClassTypeName());
        context.put("stuName", studentInfo.getName());
        context.put("day", date+"  "+weekDay);
        context.put("time", toTime);
        context.put("nowDateTime", DateUtil.now());
        context.put("remark", studentInfo.getRemark());
        context.put("stuId", studentInfo.getId());
        String appId = "wx0fa07a6c70897e68";
        String appSecret = "625080e0d87e75343781460af32c3fe7";
        context.put("appId", appId);
//        context.put("linkUrl", generateUrlLink(appId,appSecret, studentInfo.getId()));
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate("vm/massage.vm", Constants.UTF8);
        tpl.merge(context, sw);
//        System.out.println(dataMap.toString());
        String content = sw.toString();
        System.out.println(content);
        // 发送POST请求
        sendPostRequest(content,requestUrl);
    }


    /**
     * 发送POST请求
     * @param content
     * @param requestUrl
     */
    public static void sendPostRequest(String requestBody, String requestUrl) {
//        requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=0160e042-bb6d-4936-8c87-943e83a69411";
        log.info("群聊机器人URL: {}", requestUrl);
        if (StrUtil.isNotEmpty(requestUrl) && !isValidRequestUrl(requestUrl)) {
            throw new RuntimeException("群聊机器人设置为空或者格式不正确");
        }

//        String requestBody = "{\n" +
//                "    \"markdown\": {\n" +
//                "        \"content\": \"" + content + "\"\n" +
//                "    },\n" +
//                "    \"msgtype\": \"markdown\"\n" +
//                "}";


        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
//                System.out.println("POST请求成功");
                log.info("企微群聊派单消息发送成功！");
            } else {
                throw new RuntimeException("POST请求失败，响应码：" + responseCode);
            }

            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean isValidRequestUrl(String requestUrl) {
        String prefix = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";
        return requestUrl.startsWith(prefix) && requestUrl.length() > prefix.length();
    }

    /**
     * 生成微信 URL Link
     * @param appId
     * @param appSecret
     * @return
     */
    public static String generateUrlLink(String appId, String appSecret,String studentId) {
        String accessToken = getAccessToken(appId, appSecret);
        String requestUrl = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + accessToken;
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            //封装请求参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("path", "pages/home/home");
            jsonObject.put("query", studentId);
            jsonObject.put("expire_type", 1);
            jsonObject.put("expire_interval", 30);
            jsonObject.put("env_version", "release");
            // 封装 cloud_base 对象
//            JSONObject cloudBase = new JSONObject();
//            cloudBase.put("env", "xxx");
//            cloudBase.put("domain", "xxx.xx");
//            cloudBase.put("path", "/jump-wxa.html");
//            cloudBase.put("query", "a=1&b=2");
//            // 将 cloud_base 对象添加到主对象中
//            jsonObject.put("cloud_base", cloudBase);

            // 打印最终的JSONObject字符串
//            System.out.println(jsonObject.toString());

            String jsonInputString = jsonObject.toString();
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
            } else {
                throw new RuntimeException("POST请求失败，响应码：" + responseCode);
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 解析 JSON 响应
        JSONObject jsonResponse = new JSONObject(response.toString());
        return jsonResponse.getStr("url_link");
    }

    /**
     * 获取微信 access token
     * @param appId
     * @param appSecret
     * @return
     */
    public static String getAccessToken(String appId, String appSecret) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
            } else {
                throw new RuntimeException("GET请求失败，响应码：" + responseCode);
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 解析 JSON 响应
        JSONObject jsonResponse = new JSONObject(response.toString());
        return jsonResponse.getStr("access_token");
    }

}

